package com.imooc.kafka.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


/**
 * @author Gerry chan
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/kafka")
public class ProduceController {
    @Autowired
    private SimpleProducer simpleProducer;

    @Value("${kafka.topic.default}")
    private String topic;

    private Gson gson = new Gson();

    @RequestMapping(value="/hello", method = RequestMethod.GET,produces = {"application/json"})
    private Response SendKafka() {
        return new Response(ErrorCode.SUCCESS, "OK");
    }

    @RequestMapping(value="/send", method=RequestMethod.POST,produces = {"application/json"})
    private Response sendKafka(@RequestBody MessageEntity message) {
        try {
            log.info("Kafka的消息={}"， gson.toJson(message));
            simpleProducer.send(topic, "key", message);
            log.info("发送kafka成功。");
            return new Response(ErrorCode.SUCCESS,"发送kafka成功");
        } catch (Exception e) {
            log.error("发送Kafka失败", e);
            return new Response(ErrorCode.EXCEPTION, "发送kafka失败");
        }
    }



}
